package com.ccl.iot.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import com.ccl.iot.R;

/**
 * 对seekbar的图示, 扇形或者圆形
 */
public class PisitionBoundsView extends View {

    private Paint mPaint;
    private int mHeight;
    private int mWidth;
    private int mAngle;
    private RadialGradient mRadialGradient;
    private float radius = 0;

    private boolean mIsCircle;	//是否是圆形
    private int mPerc;

    public PisitionBoundsView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BoundsView);
        mIsCircle = a.getBoolean(R.styleable.BoundsView_isCircle, false);
        init();
    }

    public PisitionBoundsView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PisitionBoundsView(Context context) {
        this(context, null);
    }

    private void init(){
        mPaint = new Paint();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        radius = (mWidth > mHeight?mWidth:mHeight)/2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if(mIsCircle){
            mRadialGradient = new RadialGradient(this.getWidth()/2, this.getHeight()/2, radius*mPerc/100, new int[] {Color.RED, Color.BLACK, Color.TRANSPARENT}, null,Shader.TileMode.CLAMP);
            mPaint.setAntiAlias(true);
            mPaint.setShader(mRadialGradient);
            canvas.drawCircle(mWidth / 2, mHeight / 2, radius*mPerc/100, mPaint);
        }else{
            RectF oval = new RectF(5, 5, mWidth-5, (mHeight*2)-15);
            canvas.drawArc(oval, 210+mAngle, 120-(mAngle*2), true, mPaint);
        }

    }

    /**
     * 设置角度或范围
     * @param percenpage
     */
    public void setAngle(int percenpage){
        if(mIsCircle){
            mPerc = percenpage/2+50;
        }else{
            mAngle = (100 - percenpage)/2;
        }
        postInvalidate();
    }

    public void setColor(int color){
        if(!mIsCircle){
            mPaint.setColor(color);
        }
    }
}
